<template>
  <view class="video-preview-container">
    <!-- 设备名称栏 -->
    <view class="device-bar">
      <text class="device-label">E094154520002</text>
    </view>

    <!-- 视频播放区域 -->
    <view class="video-section">
      <video :src="liveUrl" :autoplay="true" class="video-player" :is-live="true" @error="onVideoError" :enableNative="true"></video>
    </view>

    <!-- 功能按钮区域 -->
    <view class="function-buttons">
      <view class="function-btn" @click="showInfo">
        <!-- <view class="btn-icon">ℹ️</view> -->
        <image :src="infoSrc" class="btn-icon-img"></image>
        <text class="btn-label">信息</text>
      </view>

      <view class="function-btn" @click="refreshVideo">
        <!-- <view class="btn-icon">🔄</view> -->
        <image :src="refreshSrc" class="btn-icon-img"></image>
        <text class="btn-label">刷新</text>
      </view>
      <view class="function-btn" @click="takeSnapshot">
        <!-- <view class="btn-icon">📷</view> -->
        <image :src="snapshotSrc" class="btn-icon-img"></image>
        <text class="btn-label">截图</text>
      </view>
    </view>

    <!-- 云台控制区域 -->
    <view class="control-section">
      <!-- 默认显示控制卡片 -->
      <view v-if="!showGimbalControl">
        <view class="section-header">
          <text class="section-title">云台控制</text>
        </view>
        <view class="control-grid">
          <!-- 方向控制 -->
          <view class="control-card" @click="showDirectionControl">
            <!-- <view class="card-icon">🎮</view> -->
            <image :src="directionSrc" class="card-icon-img"></image>
            <text class="card-label">方向控制</text>
          </view>
          <!-- 变焦控制 -->
          <view class="control-card" @click="showZoomControl">
            <!-- <view class="card-icon">🔍</view> -->
            <image :src="zoomSrc" class="card-icon-img"></image>
            <text class="card-label">变焦控制</text>
          </view>

          <!-- <view class="control-card" @click="showPresetControl">
            <view class="card-icon">📍</view>
            <text class="card-label">预置位</text>
          </view>
          <view class="control-card" @click="showCruiseControl">
            <view class="card-icon">🔄</view>
            <text class="card-label">巡航设置</text>
          </view> -->
        </view>
      </view>

      <!-- 云台控制面板 -->
      <view v-if="showGimbalControl" class="gimbal-panel">
        <view class="close-btn-top" @click="closeGimbalControl">✕</view>
        <view class="section-header">
          <text class="section-title">云台控制</text>
        </view>

        <!-- 方向控制面板 -->
        <view v-if="controlType === 'direction'" class="direction-control">
          <view class="direction-title">方向控制</view>
          <view class="direction-pad">
            <!-- 上 -->
            <view class="direction-btn up-btn" @touchstart="startDirectionControl('up')">
              <text class="direction-text">上</text>
            </view>

            <!-- 左、右 -->
            <view class="direction-row">
              <view class="direction-btn left-btn" @touchstart="startDirectionControl('left')">
                <text class="direction-text">左</text>
              </view>
              <view class="direction-btn right-btn" @touchstart="startDirectionControl('right')">
                <text class="direction-text">右</text>
              </view>
            </view>

            <!-- 下 -->
            <view class="direction-btn down-btn" @touchstart="startDirectionControl('down')">
              <text class="direction-text">下</text>
            </view>
          </view>
        </view>

        <!-- 变焦控制面板 -->
        <view v-if="controlType === 'zoom'" class="zoom-control">
          <!-- 变焦控制 -->
          <view class="control-group">
            <view class="group-title">变焦</view>
            <view class="group-buttons">
              <view class="group-btn zoom-in-btn" @click="zoomControl('near')">
                <text class="btn-text">放大</text>
              </view>
              <view class="group-btn zoom-out-btn" @click="zoomControl('far')">
                <text class="btn-text">缩小</text>
              </view>
            </view>
          </view>

          <!-- 光圈控制 -->
          <view class="control-group">
            <view class="group-title">光圈</view>
            <view class="group-buttons">
              <view class="group-btn aperture-open-btn" @click="apertureControl('in')">
                <text class="btn-text">开大</text>
              </view>
              <view class="group-btn aperture-close-btn" @click="apertureControl('out')">
                <text class="btn-text">关小</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { userPlay, snap, gimbalDirectionControl, gimbalZoomControl, gimbalApertureControl, getChannelInfo } from "@/apis/equipment"

export default {
  data() {
    return {
      infoSrc: require("@/static/images/xinxi.png"),
      refreshSrc: require("@/static/images/shuaxin.png"),
      snapshotSrc: require("@/static/images/jietu.png"),
      directionSrc: require("@/static/images/fangxiang.png"),
      zoomSrc: require("@/static/images/bianjiao.png"),
      deviceName: "金秋巷",
      deviceCode: "P085.0 T035.1 X1.0",
      currentTime: "2025-10-22 13:17:22",
      videoUrl: "", // 原生video地址
      liveUrl: "", // 钉钉直播地址
      isMuted: false,
      objectFit: "contain", // contain | fillCrop
      isBuffering: false,
      showCenterIcon: false,
      timer: null,
      channelId: "",
      deviceId: "",
      // 云台控制相关
      showGimbalControl: false,
      controlType: "direction", // direction | zoom
      directionTimer: null,
      zoomTimer: null,
      apertureTimer: null,
      stream: "",
    }
  },
  methods: {
    // 获取视频
    fetchUserPlay() {
      const params = { channelId: this.channelId }
      userPlay(params).then((res) => {
        this.liveUrl = res.fmp4
        console.log("this.liveUrl :>> ", this.liveUrl)
        this.videoUrl = res.fmp4
        this.stream = res.stream
      })
    },

    // 原生video错误
    onVideoError(e) {
      console.error("视频错误:", e)
    },

    // 显示信息
    showInfo() {
      const params = { id: this.channelId }
      getChannelInfo(params).then((res) => {
        console.log("res :>> ", res)
        uni.showModal({
        title: "设备信息",
        content: `设备名称: ${res.gbName}\n设备编号: ${res.gbDeviceId}\n设备厂商: ${res.gbManufacturer || ''}\n设备型号: ${res.gbModel || ''}`,
        showCancel: false,
        confirmText: "确定",
      })
      })
      
    },


    // 刷新视频
    refreshVideo() {
      this.fetchUserPlay()
    },

    // 截图
    takeSnapshot() {
      const stream = this.stream.split("_")
      const params = { channelId: stream[1], deviceId: stream[0] }
      snap(params).then((res) => {
        console.log('res :>> ', res);
        let  newUrl = res.split("/").pop()
        console.log('newUrl :>> ', newUrl);
        const url = `http://58.16.58.85:18080/api/play/getSnapImg/${newUrl}`
        uni.saveImageToPhotosAlbum({
          filePath: url,
          success: () => {
            uni.showToast({
              title: "截图成功",
              icon: "success",
            })
          },
        })
      })
    },

    // 显示方向控制
    showDirectionControl() {
      this.controlType = "direction"
      this.showGimbalControl = true
    },

    // 显示变焦控制
    showZoomControl() {
      this.controlType = "zoom"
      this.showGimbalControl = true
    },

    // 关闭云台控制弹窗
    closeGimbalControl() {
      this.showGimbalControl = false
    },

    // 开始方向控制
    startDirectionControl(direction) {
      console.log("开始方向控制:", direction)

      // 立即发送一次控制命令
      this.sendDirectionCommand(direction)
    },

    // 停止方向控制
    stopDirectionControl() {
      // 发送停止命令
      this.sendDirectionCommand("stop")
    },

    // 发送方向控制命令
    sendDirectionCommand(direction) {
      console.log("发送方向控制命令:", direction, "设备ID:", this.deviceId)
      const stream = this.stream.split("_")
      const params = {
        // channelId: stream[1],
        // deviceId: stream[0],
        channelId: this.channelId,
        // deviceId: this.deviceId,
        command: direction,
        // horizonSpeed: 255,
        // verticalSpeed: 255,
        zoomSpeed: 80,
        panSpeed: 80,
        tiltSpeed: 80,
      }
      gimbalDirectionControl(params)
        .then((res) => {
          console.log("方向控制响应:", res)
          if (direction !== "stop") {
            this.stopDirectionControl()
          }
        })
        .catch((err) => {
          console.error("方向控制失败:", err)
          uni.showToast({
            title: "控制失败",
            icon: "error",
          })
        })
    },

    // 变焦控制
    zoomControl(type) {
      console.log("变焦控制:", type)

      // 立即发送一次变焦命令
      this.sendZoomCommand(type)
    },

    // 停止变焦控制
    stopZoomControl() {
      console.log("停止变焦控制")
      if (this.zoomTimer) {
        clearInterval(this.zoomTimer)
        this.zoomTimer = null
      }
      // 发送停止变焦命令
      this.sendZoomCommand("stop")
    },

    // 发送变焦控制命令
    sendZoomCommand(type) {
      console.log("发送变焦控制命令:", type, "设备ID:", this.deviceId)
      const stream = this.stream.split("_")
      // const params = { channelId: stream[1], deviceId: stream[0] }
      const params = {
        // channelId: stream[1],
        // deviceId: stream[0],
        channelId: this.channelId,
        command: type,
        speed: 100,
      }
      gimbalZoomControl(params)
        .then((res) => {
          console.log("变焦控制响应:", res)
          if (type !== "stop") {
            this.stopZoomControl()
          }
        })
        .catch((err) => {
          console.error("变焦控制失败:", err)
        })
    },

    // 光圈控制
    apertureControl(type) {
      console.log("光圈控制:", type)

      // 立即发送一次光圈命令
      this.sendApertureCommand(type)
    },

    // 停止光圈控制
    stopApertureControl() {
      console.log("停止光圈控制")
      // 发送停止光圈命令
      this.sendApertureCommand("stop")
    },

    // 发送光圈控制命令
    sendApertureCommand(type) {
      console.log("发送光圈控制命令:", type, "设备ID:", this.deviceId)
      const stream = this.stream.split("_")
      const params = {
        // deviceId: stream[0],
        // channelId: stream[1],
        channelId: this.channelId,
        command: type,
        speed: 100,
      }
      gimbalApertureControl(params)
        .then((res) => {
          console.log("光圈控制响应:", res)
          if (type !== "stop") {
            this.stopApertureControl()
          }
        })
        .catch((err) => {
          console.error("光圈控制失败:", err)
          uni.showToast({
            title: "控制失败",
            icon: "error",
          })
        })
    },
  },
  onLoad(options) {
    // 从路由参数获取设备信息
    if (options.deviceName) {
      this.deviceName = options.deviceName
    }
    if (options.deviceCode) {
      this.deviceCode = options.deviceCode
    }

    this.channelId = options.channelId
    this.deviceId = options.deviceId
    this.fetchUserPlay()
  },
  onShow() {},
  onUnload() {
    // 清除定时器
    if (this.timer) {
      clearInterval(this.timer)
    }
    if (this.directionTimer) {
      clearInterval(this.directionTimer)
    }
    if (this.zoomTimer) {
      clearInterval(this.zoomTimer)
    }
    if (this.apertureTimer) {
      clearInterval(this.apertureTimer)
    }
  },
  created() {},
}
</script>

<style lang="less" scoped>
.video-preview-container {
  width: 100%;
  min-height: 100vh;
  background: #f5f5f5;
}

// 设备名称栏
.device-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 80rpx;
  // background: linear-gradient(135deg, #7b68ee 0%, #9370db 100%);
  background-color: #2563e1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30rpx;
  z-index: 999;

  .device-label {
    font-size: 32rpx;
    color: #fff;
    font-weight: bold;
  }

  .device-label-right {
    font-size: 28rpx;
    color: #fff;
  }
}

// 视频播放区域
.video-section {
  position: relative;
  width: 100%;
  height: 450rpx;
  background: #000;
  margin-top: 80rpx; // 88 + 80
}

.video-player {
  width: 100%;
  height: 100%;
  position: relative;
}

// 视频叠加层
.video-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
}

// 加载状态
.loading-status {
  position: absolute;
  top: 20rpx;
  left: 20rpx;
  display: flex;
  align-items: center;
  background: rgba(0, 0, 0, 0.6);
  padding: 10rpx 20rpx;
  border-radius: 30rpx;

  .loading-icon {
    width: 30rpx;
    height: 30rpx;
    margin-right: 10rpx;

    .loading-dot {
      display: block;
      width: 12rpx;
      height: 12rpx;
      background: #ff4d4f;
      border-radius: 50%;
      animation: blink 1s infinite;
    }
  }

  .loading-text {
    font-size: 24rpx;
    color: #fff;
  }
}

@keyframes blink {
  0%,
  100% {
    opacity: 1;
  }
  50% {
    opacity: 0.3;
  }
}

// 视频信息（底部左侧）
.video-info-bottom {
  position: absolute;
  bottom: 20rpx;
  left: 20rpx;
  display: flex;
  flex-direction: column;
  color: #fff;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.8);

  .video-time {
    font-size: 28rpx;
    margin-bottom: 5rpx;
  }

  .video-device {
    font-size: 24rpx;
  }
}

// 设备名称（底部右侧）
.video-name-right {
  position: absolute;
  bottom: 20rpx;
  right: 20rpx;
  color: #fff;
  font-size: 28rpx;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.8);
}

// 中心图标
.center-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  pointer-events: all;

  .play-icon {
    font-size: 60rpx;
    color: #fff;
  }
}

// 功能按钮区域
.function-buttons {
  display: flex;
  justify-content: space-around;
  background: #fff;
  padding: 30rpx 20rpx;
  margin-bottom: 20rpx;
}

.function-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;

  .btn-icon {
    width: 80rpx;
    height: 80rpx;
    background: #f5f5f5;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 40rpx;
    margin-bottom: 10rpx;
  }

  .btn-label {
    font-size: 24rpx;
    color: #666;
  }
  .btn-icon-img {
    width: 50rpx;
    height: 50rpx;
    margin-bottom: 10rpx;
  }
}

// 控制区域
.control-section {
  background: #fff;
  margin: 0 20rpx 20rpx;
  border-radius: 20rpx;
  padding: 30rpx;
}

.section-header {
  margin-bottom: 30rpx;

  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }
}

.control-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}

.control-card {
  background: #f8f8f8;
  border-radius: 16rpx;
  padding: 40rpx 30rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 180rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

  .card-icon {
    font-size: 60rpx;
    margin-bottom: 15rpx;
  }

  .card-label {
    font-size: 28rpx;
    color: #666;
    font-weight: 500;
  }
  .card-icon-img {
    width: 60rpx;
    height: 60rpx;
    margin-bottom: 15rpx;
  }
}

// 其他功能区域
.other-section {
  background: #fff;
  margin: 0 20rpx 20rpx;
  border-radius: 20rpx;
  padding: 30rpx;
}

.section-desc {
  margin-bottom: 20rpx;

  .desc-text {
    font-size: 26rpx;
    color: #999;
  }
}

.function-list {
  .function-item {
    display: flex;
    align-items: center;
    padding: 20rpx 0;

    .item-dot {
      font-size: 32rpx;
      color: #333;
      margin-right: 15rpx;
    }

    .item-text {
      font-size: 28rpx;
      color: #333;
    }
  }
}

// 云台控制面板样式
.gimbal-panel {
  position: relative;
}

// 右上角关闭按钮样式
.close-btn-top {
  position: absolute;
  top: 20rpx;
  right: 20rpx;
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  background: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  color: #666;
  z-index: 10;
}

// 方向控制样式
.direction-control {
  .direction-title {
    font-size: 28rpx;
    color: #333;
    text-align: center;
    margin-bottom: 40rpx;
  }

  .direction-pad {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    grid-template-rows: 1fr 1fr 1fr;
    gap: 8rpx;
    width: 320rpx;
    height: 320rpx;
    margin: 0 auto;
  }

  .direction-row {
    display: contents;
  }

  .direction-btn {
    width: 100rpx;
    height: 100rpx;
    border-radius: 20rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28rpx;
    font-weight: bold;
    color: #fff;
    box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.2);
    transition: all 0.2s ease;

    &:active {
      transform: scale(0.95);
    }

    &.up-btn {
      background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
      grid-column: 2;
      grid-row: 1;
    }

    &.down-btn {
      background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
      grid-column: 2;
      grid-row: 3;
    }

    &.left-btn {
      background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
      grid-column: 1;
      grid-row: 2;
    }

    &.right-btn {
      background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
      grid-column: 3;
      grid-row: 2;
    }
  }

  .direction-text {
    font-size: 28rpx;
    color: #fff;
    font-weight: bold;
  }
}

.control-group {
  margin-bottom: 40rpx;

  &:last-child {
    margin-bottom: 0;
  }

  .group-title {
    font-size: 28rpx;
    color: #333;
    text-align: center;
    margin-bottom: 20rpx;
    font-weight: bold;
  }

  .group-buttons {
    display: flex;
    gap: 30rpx;
  }

  .group-btn {
    flex: 1;
    height: 80rpx;
    border-radius: 16rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24rpx;
    font-weight: bold;
    color: #fff;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
    transition: all 0.2s ease;

    &:active {
      transform: scale(0.95);
    }

    // 变焦按钮
    &.zoom-in-btn {
      background: linear-gradient(135deg, #4caf50 0%, #66bb6a 100%);
    }

    &.zoom-out-btn {
      background: linear-gradient(135deg, #ff9800 0%, #ffb74d 100%);
    }

    // 光圈按钮
    &.aperture-open-btn {
      background: linear-gradient(135deg, #9c27b0 0%, #ba68c8 100%);
    }

    &.aperture-close-btn {
      background: linear-gradient(135deg, #e91e63 0%, #f48fb1 100%);
    }
  }

  .btn-text {
    font-size: 24rpx;
    color: #fff;
    font-weight: bold;
  }
}
</style>
